<template>
	<view class="studyDetailPage">
		<u-status-bar></u-status-bar>
		<u-navbar @leftClick="goCustomNavBack" title=" " bgColor="transparent" :autoBack="true" leftIconColor="#fff"
			titleStyle="color:#fff;text">
		</u-navbar>
		<view class="studyContent" v-if="isLoad">
			<u-sticky offset-top="0">
				<view class="videoContent">
					<video :src="videoUrl" :muted="true" :show-mute-btn="true" play-btn-position="center"
						:autoplay="selectIndex===0?false:true" :enable-play-gesture="true" :show-casting-button="true" :show-screen-lock-button="true"
						:show-snapshot-button="true" style="width: 100vw;height: 50vw;" @play="doWatch"
						@ended="watchEnd"></video>
				</view>
				<view class="videoTitle">
					<view class="titleContent">
						<view class="title">列表</view>
						<view class="titleOperate" @click="doFilter">
							<view>{{ascending?'升序':'降序'}}</view>
							<view :class="ascending?'ascendIcon':'ascendIcon descend'">
								<u--image src="/static/growup/7.png" shape="square" mode="aspectFill" width="28rpx"
									height="28rpx">
								</u--image>
							</view>
						</view>
					</view>
				</view>
			</u-sticky>
			<view class="videoList">
				<u-empty mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png"
					v-if="!list.length && !isLoading" text="没有视频"></u-empty>
				<view class="list" v-for="(item,index) in list" :key="index" @click="changeVideo(item,index)">
					<view class="index">{{index+1}}</view>
					<view class="detail">
						<view class="name">{{item.courseName}}</view>
						<view class="content">
							<view>{{item.createTime}}</view>
							<view class="count">
								播放：{{item.playbackVolume||0}}
							</view>
							<view class="count">
								时长：{{item.duration||'未知'}}
							</view>
						</view>
					</view>
					<view class="status" :class="(item.vpoints==='0' ||item.isExchange)?'':'orange'"
						@click="doChange(item)">
						{{item.vpoints==='0'?'免费':(item.isExchange?'已兑':'兑换')}}
					</view>
				</view>
				<u-loadmore v-if="list.length" :status="isFinish?'nomore':'loading'" loading-text="正在加载"
					loadmore-text="加载更多" nomore-text="没有更多了" color="#d0d0d0" />
			</view>
		</view>
		<u-popup :show="showExchange" :round="10" mode="bottom" @close="doClose">
			<view class="exchangePanel">
				<view class="title">积分兑换</view>
				<view class="cost">{{exchangeInfo.vpoints}}
					<view class="unit">积分</view>
				</view>
				<view class="detail">
					<view class="userScore" v-if="exchangeInfo.canExchange">当前积分{{userScore}}</view>
					<view class="userScore" v-if="!exchangeInfo.canExchange">当前积分不足，请到任务中心获取积分</view>
					<view class="vBtn" @click="doExchange(exchangeInfo)">{{exchangeInfo.btnText}}</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				id: "",
				baseUrl: this.$api.baseUrl,
				isLoad: false,
				ascending: true,
				showExchange: false,
				exchangeInfo: {
					cost: "0",
					canExchange: false,
					btnText: "做任务"
				},
				userScore: 0,
				list: [],
				pageNo: 1,
				pageSize: 10,
				total: 0,
				isFinish: false,
				isLoading: false,
				userId: "",
				videoUrl: "",
				videoId: "",
				playArr: [],
				hasLoad: false,
				selectIndex: 0
			}
		},
		onLoad(option) {
			uni.getStorage({
				key: "userInfo",
				success: (userInfo) => {
					this.userId = userInfo.data.id;
					this.$request.get(this.$api.getUserById, {
						id: this.userId
					}).then(result => {
						this.userScore = result.result.integral;
						uni.hideLoading()
					})
					this.id = option.id;
					this.initData();
				},
			})
		},
		onReachBottom() {
			if (!this.isLoading && !this.isFinish) {
				this.pageNo++;
				this.initData();
			}
		},
		methods: {
			initData(isRefresh) {
				this.isLoading = true;
				Promise.all([
					this.$request.get(this.$api.studyDetail, {
						type: this.ascending ? '1' : '2',
						pageNo: this.pageNo,
						pageSize: this.pageSize,
						curriculumId: this.id,
						userId: this.userId
					}),
				]).then(res => {
					uni.hideLoading()
					if (isRefresh) {
						uni.stopPullDownRefresh()
					}
					this.isLoading = false;
					this.list = this.list.concat(res[0].result.records);
					//首次加载找到一个免费的视频或者已经兑换的视频进行加载
					if (!this.isLoad) {
						this.list.map(item => {
							if (item.isExchange || item.vpoints === "0" && !this.videoUrl && !this
								.hasLoad) {
								this.hasLoad = true;
								// uni.downloadFile({
								// 	url: this.baseUrl + '/sys/common/static/' + item.uploadVideo,
								// 	success: (res) => {
								// 		console.log(res)
								// 		var temp = res.tempFilePath
								// 		this.videoUrl = temp
								// 		this.videoId = item.id
								// 	}
								// })
								this.videoUrl = item.uploadVideo
								this.videoId = item.id
							}
						})
					}
					this.total = res[0].result.total;
					if (this.pageNo * this.pageSize < this.total) {
						this.isFinish = false
					} else {
						this.isFinish = true
					}
					this.isLoad = true;

					let index = this.playArr.indexOf(this.id);
					if (index === -1) {
						this.$request.get(this.$api.videoCountList, {
							id: this.id,
							userId: this.userId
						}).then(res => {
							console.log("阅读量+1")
							this.playArr.push(this.id)
							uni.hideLoading()
						})
					}
				})
			},
			doSearch() {
				this.isFinish = false;
				if (!this.isLoading) {
					this.pageNo = 1;
					this.list = [];
					this.initData(true);
				}
			},
			doFilter() {
				this.ascending = !this.ascending;
				this.doSearch();
			},
			doChange(item) {
				if (item.vpoints === '0') return;
				this.showExchange = true;
				if (item.vpoints > this.userScore) {
					this.exchangeInfo.id = item.id;
					this.exchangeInfo.canExchange = false;
					this.exchangeInfo.btnText = "做任务"
					this.exchangeInfo.vpoints = item.vpoints
				} else {
					this.exchangeInfo.id = item.id;
					this.exchangeInfo.canExchange = true;
					this.exchangeInfo.btnText = "立即兑换"
					this.exchangeInfo.vpoints = item.vpoints
				}
			},
			doClose() {
				this.showExchange = false
			},
			refreshUser() {
				this.isFinish = false;
				if (!this.isLoading) {
					this.pageNo = 1;
					this.list = [];
					this.isLoading = true;
					Promise.all([
						this.$request.get(this.$api.studyDetail, {
							type: this.ascending ? '1' : '2',
							pageNo: this.pageNo,
							pageSize: this.pageSize,
							curriculumId: this.id,
							userId: this.userId
						}),
					]).then(res => {
						this.isLoading = false;
						this.list = this.list.concat(res[0].result.records);
						this.total = res[0].result.total;
						if (this.pageNo * this.pageSize < this.total) {
							this.isFinish = false
						} else {
							this.isFinish = true
						}
						this.$request.get(this.$api.getUserById, {
							id: this.userId
						}).then(result => {
							this.userScore = result.result.integral;
						})
						uni.showToast({
							title: "兑换成功",
							icon: "none"
						})
						this.showExchange = false;
						uni.hideLoading()
					})
				}
			},
			doExchange(item) {
				if (item.vpoints > this.userScore) {
					uni.navigateTo({
						url: "/pages/taskCenter/taskCenter"
					})
				} else {
					this.$request.post(this.$api.doExchange, {
						integral: item.vpoints,
						otherId: item.id,
						userId: this.userId,
						exchangeType: 3
					}).then(res => {
						this.refreshUser();
						uni.hideLoading()
					})
				}
			},
			//列表点击切换
			changeVideo(item, index) {
				this.videoUrl = this.baseUrl + '/sys/common/static/' + item.uploadVideo
				if (item.isExchange || item.vpoints === "0") {
					/* uni.downloadFile({
						url: this.baseUrl + '/sys/common/static/' + item.uploadVideo,
						success: (res) => {
							var temp = res.tempFilePath
							this.videoUrl = temp
							this.videoId = item.id
						}
					}) */
					this.videoUrl = item.uploadVideo
					this.videoId = item.id
					this.selectIndex = index
				} else {
					this.doChange(item)
				}
			},
			//视频点击播放
			doWatch() {
				let index = this.playArr.indexOf(this.videoId);
				if (index === -1) {
					this.$request.get(this.$api.videoCount, {
						id: this.videoId,
						userId: this.userId
					}).then(res => {
						console.log("阅读量+1")
						this.playArr.push(this.videoId)
						uni.hideLoading()
					})
				}
			},
			//播放结束
			watchEnd() {
					if (this.selectIndex !== this.list.length - 1) {
						uni.showToast({
							title:"即将播放："+(this.list[this.selectIndex + 1].courseName),
							icon:"none"
						})
						setTimeout(()=>{
							this.changeVideo(this.list[this.selectIndex + 1], this.selectIndex + 1)
						},2000)
					}
			}
		}
	}
</script>

<style lang="scss">
	.studyDetailPage {
		min-height: 100vh;
		background-color: #fff;

		.u-navbar--fixed {
			z-index: 999 !important;
		}

		.studyContent {
			.videoContent {
				width: 100vw;
				display: flex;
				justify-content: center;
			}

			.videoTitle {
				padding: 0 40rpx;
				display: flex;
				flex-direction: column;
				background-color: #fff;

				.titleContent {
					display: flex;
					justify-content: space-between;
					border-bottom: 1rpx solid #eee;
					background-color: #fff;

					.title {
						font-size: 32rpx;
						font-family: PingFang SC-Regular, PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 88rpx;
					}

					.titleOperate {
						display: flex;
						justify-content: flex-end;
						color: #707070;
						align-items: center;
						line-height: 88rpx;
						font-size: 26rpx;

						.ascendIcon {
							margin-left: 10rpx;
						}

						.descend {
							transform: rotate(180deg);
						}
					}
				}
			}

			.videoList {
				padding: 0 40rpx 60rpx;
				display: flex;
				flex-direction: column;
				background-color: #fff;

				.list {
					display: flex;
					border-bottom: 1rpx solid #eee;
					justify-content: flex-start;
					font-size: 28rpx;
					font-family: PingFang SC-Medium, PingFang SC;
					font-weight: 500;
					color: #333333;
					padding: 20rpx 0;
					align-items: center;

					.index {
						width: 40rpx;
					}

					.detail {
						display: flex;
						justify-content: flex-start;
						flex-direction: column;
						width: calc(100% - 120rpx);
						line-height: 50rpx;

						.name {
							font-weight: 500;
						}

						.content {
							display: flex;
							flex-wrap: nowrap;
							justify-content: flex-start;
							font-size: 24rpx;
							font-family: PingFang SC-Regular, PingFang SC;
							font-weight: 400;
							color: #999999;

							.count {
								padding-left: 40rpx;
							}
						}
					}

					.status {
						width: 60rpx;
						padding-left: 20rpx;
						text-align: right;
						font-size: 24rpx;
						font-family: PingFang SC-Regular, PingFang SC;
						font-weight: 400;
						color: #666666;
					}

					.orange {
						color: #EC6C2F;
					}
				}
			}
		}

		.exchangePanel {
			display: flex;
			text-align: center;
			flex-direction: column;

			.title {
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				color: #666666;
				font-size: 28rpx;
				border-bottom: 1rpx solid #eee;
				height: 100rpx;
				line-height: 100rpx;
			}

			.cost {
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				color: #333333;
				font-size: 46rpx;
				color: #EC6C2FFF;
				display: flex;
				flex-wrap: nowrap;
				justify-content: center;
				border-bottom: 1rpx solid #eee;
				height: 100rpx;
				line-height: 100rpx;

				.unit {
					font-size: 24rpx;
					position: relative;
					top: 6rpx;
					left: 2rpx;
					color: #333333FF;
				}
			}

			.detail {
				line-height: 100rpx;
				display: flex;
				align-items: center;
				flex-direction: column;
				padding-bottom: 40rpx;

				.userScore {
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #999999;
					font-size: 30rpx;
				}

				.vBtn {
					background: linear-gradient(180deg, #87C5FC 0%, #247FFF 100%);
					border-radius: 48rpx;
					font-family: PingFang SC-Bold, PingFang SC;
					font-weight: bold;
					color: #FFFFFF;
					font-size: 34rpx;
					height: 96rpx;
					width: 680rpx;
				}
			}
		}
	}
</style>
